#include "client_impl.h"
#include "../inc/logger.h"
#ifdef _WIN32
#include "../desktop/desktop.h"
#endif

#ifdef _WIN32

bool run=false;

unsigned int __stdcall Safeguard(void *arg)
{
	while(run)
	{
		if(!IsQServerExist(false))
		{
			LOG4_INFO("Safeguard thread found QServer not exits");
		    StartupQServer();
		}
		Sleep(1000);
	}
	LOG4_INFO("Safeguard thread stoped");
	return 0;
}

int DesktopAppInit(wchar_t* serverpath,bool safeguard)
{
	LOG4_INFO("Client init");
	if(run)
		return 0;
	if(!CMainCacheApp::GetInstance().Init(serverpath))
	{
		LOG4_ERROR("Create share memory failed.");
		return -1;
	}

	if(!IsQServerExist())
		StartupQServer();
	else
	{
		int count=0;
		while(!IsQServerOK(false))
		{
			count++;
			if(count>20)
				break;
		    Sleep(100);
		}
		if(!IsQServerOK(false))
		{
			KillQServer();
			StartupQServer();
		}
	}
	BOOL ok=IsQServerOK();
	int count=0;
	while(!ok)
	{
		Sleep(100);
		count++;
		if(count>20)
			break;
		ok=IsQServerOK();
	}
	if(!ok)
	{
		LOG4_ERROR("Startup QServer failed!");
		return -1;
	}
	run=true;
	if(safeguard)
	    HANDLE handle = (HANDLE)_beginthreadex(NULL, 0, Safeguard, NULL, 0, NULL);
	LOG4_INFO("Client init ok");

	return 0;
}

int  KillServer()
{
	run=false;
	LOG4_INFO("Prepare kill qserver");
	Sleep(500);
	KillQServer();
	return 0;
}

int  DesktopAppRelease()
{
	google::protobuf::ShutdownProtobufLibrary(); 
	LOG4_INFO("Client release");
	run=false;
	return 0;
}

#endif